const Sequelize = require('sequelize')
const { database } = require('../config/config')

const { dbName, host, port, user, password } = database

const sequelize = new Sequelize(dbName, user, password, {
  host,
  port,
  dialect: 'mysql',
  // dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
  logging: true,
  dialectOptions: {
    dateStrings: true, // 禁止mysql的转换
    typeCast(field, next) { // 覆盖了sequelize的转换，看代码，目前只影响date和GEOMETRY,所以加上DATETIME类型
      if(field.type === 'DATETIME') {
        return field.string()
      }
      return next()
    }
  },
  timezone: '+08:00',  
  define: {
    timestamps: true, // 会自动生成 createAt和updateAt
    freezeTableName: true  // 不将表格名称复数化
  }
})

sequelize.sync()

// Note: using `force: true` will drop the table if it already exists
// sequelize.sync({force: true})

sequelize.authenticate().then(() => {
  console.log('数据库连接成功.')
}).catch(err => {
  console.error('数据库连接失败:', err)
})

module.exports = { sequelize }